<script lang="ts">
import { Message, Money, Tickets, Star, User, SwitchButton, CaretBottom, UserFilled, Notebook } from '@element-plus/icons-vue'

import { ComponentSize, ElMessage, ElMessageBox } from 'element-plus';

import { onMounted, ref } from 'vue'
import { useTokenStore } from '@/stores/token'

//导入接口函数
import { userInfoGetService } from '@/api/user.js'
//导入pinia
import { useUserInfoStore } from '@/stores/userInfo.js'
import { communityService } from '@/api/community';
import router from '@/router';
import { getUserOrderTasks, updateTaskOrderStatus } from '@/api/task.js'
const userInfoStore = useUserInfoStore();

//获取个人信息
const getUserInfo = async () => {
    let result = await userInfoGetService();
    //存储pinia
    userInfoStore.info = result.data;
}

const currentPage4 = ref(1)
const pageSize4 = ref(5)
const size = ref<ComponentSize>('default')

const pageNum = ref(1)
const pageSize = ref(10)

const handleSizeChange = (val: number) => {
    pageSize.value = val
    getOrderTasks()
}
const handleCurrentChange = (val: number) => {
    pageNum.value = val
    getOrderTasks()
}

const handleOpen = (key: string, keyPath: string[]) => {
    console.log(key, keyPath)
}
const handleClose = (key: string, keyPath: string[]) => {
    console.log(key, keyPath)
}

const getCommunity = async () => {}
getCommunity();
const posts = ref([
    {
        "id": '',
        "content": "",
        "postType": "",
        "likeCount": 0,
        "viewCount": 0,
        "videoUrl": "",
        "coverImg": null,
        "createTime": "",
        "updateTime": "",
        "title": ""
    }
])

const updateLocalStorage = () => {
    const likedPosts = posts.value.reduce((acc, post) => {
        acc[post.id] = { likeCount: post.likeCount, viewCount: post.viewCount };
        return acc;
    }, {});
    localStorage.setItem('likedPosts', JSON.stringify(likedPosts));
};

const loadLikedPosts = () => {
    const likedPosts = JSON.parse(localStorage.getItem('likedPosts')) || {};
    posts.value.forEach(post => {
        if (likedPosts[post.id]) {
            post.likeCount = likedPosts[post.id].likeCount;
            post.viewCount = likedPosts[post.id].viewCount;
        }
    });
};

const tasks = ref([])
const total = ref(0)
const loading = ref(false)

// 修改获取任务方法，添加 loading 控制
const getOrderTasks = async () => {
    loading.value = true
    try {
        const params = {
            pageNum: pageNum.value,
            pageSize: pageSize.value
        }
        const result = await getUserOrderTasks(params);
        
        if (!result) {
            console.error('API 返回结果为空');
            return;
        }
        
        if (result.code === 0) {
            tasks.value = result.data || [];
            total.value = result.data?.length || 0;
            
            if (tasks.value.length === 0) {
                ElMessage.info('暂无接单任务');
            }
        } else {
            ElMessage.error(result.msg || '获取任务失败');
        }
    } catch (error) {
        console.error('获取接单任务失败:', error);
        ElMessage.error(error.response?.data?.message || '获取任务失败，请重试');
    } finally {
        loading.value = false
    }
}

const handleCommand = (command) => {
    if (command === 'logout') {
        //退出登录
        ElMessageBox.confirm(
            '你确认退出登录吗？',
            '温馨提示',
            {
                confirmButtonText: '确认',
                cancelButtonText: '取消',
                type: 'warning',
            }
        )
        .then(() => {
            const tokenStore = useTokenStore();
            tokenStore.removeToken();
            router.push('/login');
        })
        .catch(() => {
            ElMessage({
                type: 'info',
                message: '取消退出',
            });
        });
    }
}

export default {
    components: {
        Message,
        Money,
        Tickets,
        Star,
        User,
        SwitchButton,
        CaretBottom,
        UserFilled,
        Notebook,
    },
    setup() {
        onMounted(async () => {
            try {
                await getUserInfo();
                await getOrderTasks();
            } catch (error) {
                console.error('初始化数据失败:', error);
            }
        });
        
        return {
            tasks,
            total,
            pageNum,
            pageSize,
            loading,
            handleSizeChange,
            handleCurrentChange,
            getOrderTasks,
        }
    },
    data() {
        return {
            handleOpen: '',
            handleClose: '',
            activeIndex: '2',
            searchQuery: '',
            isDark: false,
            currentPage4,
            pageSize4,
            size,
            posts,
            handleLike: '',
            handlefavorite: '',
            User,
            SwitchButton,
            UserFilled,
            Notebook,
            userInfoStore,
            userAvatar: 'https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif',
            handleSelect: '',
            recharge: '',
            withdraw: '',
            handleCommand,
        }
    },
    methods: {
        setDefaultLogo(event) {
            event.target.src = 'images/default-logo.jpg';
        },
        search() {
            // 处理搜索逻辑
            console.log(`搜索内容: ${this.searchQuery}`);
        },
        filter(option) {
            // 处理过滤逻辑
            console.log(`过滤选项: ${option}`);
        },
        navigateTologin(page) {
            this.$router.push(`/${page}`); // 跳转到登录页面
        },
        navigateToregister(page) {
            this.$router.push(`/${page}`); // 跳转到登录页面
        },
        navigateTo(link) {
            window.location.href = link;
        },
        getStatusType(status) {
            const types = {
                '进行中': 'warning',
                '已完成': 'info',
                '已取消': 'danger',
                '待确认': 'info'
            }
            return types[status] || 'default'
        },
        async handleComplete(row) {
            try {
                await ElMessageBox.confirm(
                    '确认完成该任务吗？',
                    '提示',
                    {
                        confirmButtonText: '确认',
                        cancelButtonText: '取消',
                        type: 'success'
                    }
                );
                
                await updateTaskOrderStatus(row.taskId, '已完成');
                ElMessage.success('任务已完成');
                await this.getOrderTasks();
            } catch (error) {
                if (error !== 'cancel') {
                    console.error('完成任务失败:', error);
                    ElMessage.error('操作失败，请重试');
                }
            }
        },
        async handleCancel(row) {
            try {
                await ElMessageBox.confirm(
                    '确认取消该任务吗？',
                    '提示',
                    {
                        confirmButtonText: '确认',
                        cancelButtonText: '取消',
                        type: 'warning'
                    }
                );
                
                await updateTaskOrderStatus(row.taskId, '已取消');
                ElMessage.success('任务已取消');
                await this.getOrderTasks();
            } catch (error) {
                if (error !== 'cancel') {
                    console.error('取消任务失败:', error);
                    ElMessage.error('操作失败，请重试');
                }
            }
        },
    }
}
</script>

<template>
    <el-menu :default-active="activeIndex" class="el-menu-demo" mode="horizontal" :ellipsis="false"
        @select="handleSelect" style="height:75px;box-shadow: 0 2px 4px rgba(0,0,0,0.1);">
        <el-menu-item index="0">
            <img style="width: 100px;height: 70px;margin-left: 53px;margin-right: 10px;" src="@/assets/logo.jpg"
                alt="CodeCash" />
        </el-menu-item>
        <el-search-item index="1" style="transform: translate(-100%,15px);">
            <el-input v-model="searchQuery" style="width: 300px;height:40px;" placeholder="搜索您感兴趣的内容" clearable />
            <el-button type="search" style="height: 40px;background-color:#007bff;color:white;">搜索</el-button>
        </el-search-item>
        <el-router-menu index="2" style="transform: translateX(-2%);">
            <el-link href="/" style="color: black; font-size: 18px;padding: 20px;">首页</el-link>
            <el-link href="/programmer" style="color: black; font-size: 18px;padding: 20px;">程序员</el-link>
            <el-link href="/task" style="color: black; font-size: 18px;padding: 20px;">任务大厅</el-link>
            <el-link href="/community" style="color: black; font-size: 18px;padding: 20px;">社区</el-link>
            <el-link href="/user/call" style="color: black; font-size: 18px;padding: 20px;">联系我们</el-link>
        </el-router-menu>
        <el-buttons-item index="3" style="transform: translateY(25%);margin-right: 20px;">
            <el-dropdown placement="bottom-end">
                <el-avatar :src="userAvatar" size="medium" />
                <el-icon>
                    <CaretBottom />
                </el-icon>
                <template #dropdown>
                    <el-dropdown-menu>
                        <el-dropdown-item command="userInfo" :icon="User"
                            @click="navigateTo('/userInfo')">个人中心</el-dropdown-item>
                        <el-dropdown-item command="logout" :icon="SwitchButton"
                            @click="handleCommand('logout')">退出登录</el-dropdown-item>
                    </el-dropdown-menu>
                </template>
            </el-dropdown>
        </el-buttons-item>
    </el-menu>
    <el-aside width="200px" height="700vh" style="margin-left: 300px;">
        <div
            style="margin-left: -40px;margin-top: 20px;align-items: center;justify-content: center;display: flex;flex-direction: column;">
            <el-avatar src="https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif" />
            <h5 class="mb-2">{{ userInfoStore.info.username }}</h5>
            <el-button color="#2994F2">已签约</el-button>
        </div>
        <el-divider />
        <el-menu default-active="5" class="el-menu-vertical-demo" @open="handleOpen" @close="handleClose">
            <el-menu-item index="1" @click="navigateTo('/userInfo')">
                <el-icon>
                    <Money />
                </el-icon>
                <span>账户金额</span>
            </el-menu-item>
            <el-menu-item index="2" @click="navigateTo('/userInfo/message')">
                <el-icon>
                    <Message />
                </el-icon>
                <span>账户信息</span>
            </el-menu-item>
            <el-menu-item index="3" @click="navigateTo('/userInfo/task')">
                <el-icon>
                    <Notebook />
                </el-icon>
                <span>我的任务</span>
            </el-menu-item>
            <el-menu-item index="4" @click="navigateTo('/userInfo/favorite')">
                <el-icon>
                    <Star />
                </el-icon>
                <span>我的收藏</span>
            </el-menu-item>
            <el-menu-item index="5" @click="navigateTo('')">
                <el-icon>
                    <Tickets />
                </el-icon>
                <span>订单列表</span>
            </el-menu-item>
        </el-menu>
    </el-aside>
    
    <el-footer>
        <div class="footer">
            <div>
                <a href="#">动态公告</a> |
                <a href="#">帮助</a> |
                <a href="#">关于我们</a> |
                <a href="#">合作伙伴</a> |
                <a href="#">意见反馈</a> |
                <text style="color: rgb(78, 77, 77);">@“码上有钱”程序员接单平台</text>
            </div>
            <div class="credits">
                粤ICP备20220901号-4 | 粤公网安备33011002011599号
            </div>
        </div>
    </el-footer>

    <div class="task-container">
        <div class="task-content">
            <el-table :data="tasks" style="width: 100%" height="400" :max-height="400" :scrollbar-always-on="true"
                v-loading="loading"
                element-loading-text="加载中..."
            >
                <el-table-column label="任务标题" prop="taskTitle" min-width="150"></el-table-column>
                <el-table-column label="任务内容" prop="taskContent" min-width="120">
                    <template #default="{ row }">
                        <el-tooltip
                            :content="row.taskContent"
                            placement="top"
                            :hide-after="2000"
                        >
                            <span>{{ row.taskContent }}</span>
                        </el-tooltip>
                    </template>
                </el-table-column>
                <el-table-column label="预算" prop="budget" width="100">
                    <template #default="{ row }">
                        <span>￥{{ row.budget }}</span>
                    </template>
                </el-table-column>
                <el-table-column label="状态" prop="status">
                    <template #default="{ row }">
                        <el-tag :type="getStatusType(row.status)">
                            {{ row.status }}
                        </el-tag>
                    </template>
                </el-table-column>
                <el-table-column label="接单时间" prop="acceptedTime" width="180">
                    <template #default="{ row }">
                        {{ new Date(row.acceptedTime).toLocaleString() }}
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="150">
                    <template #default="{ row }">
                        <div class="operation-buttons">
                            <el-button 
                                v-if="row.status === '进行中' || row.status === 'PROCESSING'"
                                type="success" 
                                link
                                @click="handleComplete(row)"
                            >
                                完成
                            </el-button>
                            <el-button 
                                v-if="row.status === '进行中' || row.status === 'PROCESSING'"
                                type="danger" 
                                link
                                @click="handleCancel(row)"
                            >
                                取消
                            </el-button>
                            <span v-if="row.status !== '进行中' && row.status !== 'PROCESSING'" style="color: #909399;">-</span>
                        </div>
                    </template>
                </el-table-column>
                <template #empty>
                    <el-empty description="暂无接单任务" />
                </template>
            </el-table>
            
            <el-pagination 
                v-model:current-page="pageNum"
                v-model:page-size="pageSize"
                :page-sizes="[5, 10, 15, 20]"
                :total="total"
                layout="total, sizes, prev, pager, next, jumper"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                class="pagination"
            />
        </div>
    </div>
</template>

<style>
.el-menu--horizontal>.el-menu-item:nth-child(1) {
    margin-right: auto;
}

.box-card {
    border-radius: 8px;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
    border: 1px solid white;
    align-items: center;
    justify-content: center;
    width: 65%;
    height: auto;
    margin-right: 400px;
    flex-direction: column;
    margin: auto;
}


.card-body {
    margin-left: 100px;
    margin-top: -90px;
}

.card-body p {
    word-wrap: break-word;
    /* 在需要时换行 */
    overflow-wrap: break-word;
    /* 现代浏览器支持 */
}

.card-foot {
    margin-top: -40px;
    margin-left: 600px;
    display: flex;
    position: absolute;
}

.footer {
    margin-top: 300px;
    padding: 10px 0;
    border-top: 1px solid #ddd;
    text-align: center;
}

.footer a {
    text-decoration: none;
    color: rgb(78, 77, 77);
    background: transparent;
    border: none;
    cursor: pointer;
}

.footer .credits {
    margin-top: 5px;
    font-size: 12px;
    color: gray;
}

.task-container {
    position: absolute;
    top: 150px;
    left: 520px;
    right: 20px;
    bottom: 20px;
    padding: 20px;
}

.task-content {
    border-radius: 8px;
    padding: 20px;
    height: calc(100% - 40px);
    display: flex;
    flex-direction: column;
}

.el-table {
    flex: 1;
    margin-bottom: 20px;
}

.pagination {
    display: flex;
    justify-content: center;
    margin-top: 20px;
}

.operation-buttons {
    display: flex;
    gap: 8px;
    align-items: center;
}

.operation-buttons .el-button {
    padding: 4px 8px;
    margin: 0;
}
</style>